const Controller = require('./base');

var list = [
    { pid: 4, "name": "交易查询", "path": "/order/trade" },
    { pid: 4, "name": "售后评价", "path": "/order/comment" },
    { pid: 4, "name": "售后维权", "path": "/order/protection" },
]

function toInt(str) {
    if (typeof str === 'number') return str;
    if (!str) return str;
    return parseInt(str, 10) || 0;
}
class MenuController extends Controller {
    /**
     *  
     */
    async index() {
        const ctx = this.ctx;
        const query = {
            attributes: [
                'id', ['name', 'title'], 'path', 'key', 'pid'
            ]
        };

        query.where = {
            self_state: 1
        }
        var modelData = await ctx.model.Menu.findAll(query);
        var bodyData = []
        modelData.forEach(val => {
            bodyData.push(val)
        })
        var pdata = bodyData.filter(val => { return val.pid == 0 })
        var resdata = []
        pdata.forEach((val,) => {
            var data = {
                ...val.dataValues
            }
            var list = []
            bodyData.forEach(v => {
                if (val.id == v.pid) {
                    list.push(v)
                }
            })
            data.children = list
            resdata.push(data)
        })
        this.success(resdata)
    }

    async show() {
        const ctx = this.ctx;
        ctx.body = await ctx.model.Menu.findByPk(toInt(ctx.params.id));

    }

    async create() {
        const ctx = this.ctx;
        list.forEach(async val => {
            await ctx.model.Menu.create({ ...val });

        })
        ctx.status = 201;
        ctx.body = '初始化';
    }

    async update() {
        const ctx = this.ctx;
        const id = toInt(ctx.params.id);
        const user = await ctx.model.Menu.findByPk(id);
        if (!user) {
            ctx.status = 404;
            return;
        }

        const { name, age } = ctx.request.body;
        await user.update({ name, age });
        ctx.body = user;
    }

    async destroy() {
        const ctx = this.ctx;
        const id = toInt(ctx.params.id);
        const user = await ctx.model.Menu.findByPk(id);
        if (!user) {
            ctx.status = 404;
            return;
        }

        await user.destroy();
        ctx.status = 200;
    }
}

module.exports = MenuController;